import { addRoutes, router } from '@/router'
import useUserStore from '@/store/user'
import { getToken } from '@/utils/cookie'
import { toast } from '@/utils/elnotification'
import nprogress from 'nprogress'
import { storeToRefs } from 'pinia'

//全局前置守卫
//优化菜单加载速度
let hasGetInfo = false
router.beforeEach(async (to, from, next) => {
  //显示loading
  nprogress.start()

  const token = getToken()

  //没有登录，强制跳转回登录页
  if (!token && to.path != '/login') {
    toast('请先登录')
    return next({ path: '/login' })
  }

  //防止重复登录
  if (token && to.path == '/login') {
    toast('请勿重新登录', 'error')
    return next({ path: from.path ? from.path : '/' })
  }

  //如果用户登录了，则获取用户信息并且存储在pinia中
  let hasNewRoutes = false
  if (token && !hasGetInfo) {
    const userStore = useUserStore()
    await userStore.getUserInfo()
    const { menus } = storeToRefs(userStore)
    hasGetInfo = true
    //动态添加路由
    hasNewRoutes = addRoutes(menus.value)
  }

  hasNewRoutes ? next(to.fullPath) : next()
})

//全局后置路由守卫
router.afterEach((to) => {
  //关闭loading
  nprogress.done()

  //设置页面标题
  document.title = `Sokach商城后台-${to.meta.title}`
})
